import { Message } from 'element-ui'

/**
 * download settings
 * @param {obj} res
*/

export function download(res) {
  const type = res.data.type || null
  if (type === 'application/json') {
    const reader = new FileReader()
    reader.onload = e => {
      let result = {}
      result = JSON.parse(e.target.result) // 序列化read函数中result结果
      if (result.code === '-1') {
        Message({
          type:'warning',
          message:result.msg||'下载失败'
        })
      }
    }
    reader.readAsText(res.data) // Blob数据格式通过readAsText转为JSON
    return
  }
  const blob = new Blob([res.data])
  const fileName = decodeURI(res.headers['content-disposition']) // header返回的文件名做二次处理
  const index = fileName.lastIndexOf('=') // 截取 = 所在位置后的字符串
  const fileNameStr = fileName.substring(index + 1, fileName.length)
  const elink = document.createElement('a')
  elink.download = fileNameStr
  elink.style.display = 'none'
  elink.target = '_blank'
  elink.href = URL.createObjectURL(blob)
  document.body.appendChild(elink)
  elink.click()
  URL.revokeObjectURL(elink.href) // 释放URL对象
  document.body.removeChild(elink)
}
